<?php
/*
The Knowledge Ferret - Document Explorer
Copyright (C) 2010 David R. Pratten

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
$trans = get_html_translation_table(HTML_ENTITIES);
$trans = array_slice($trans,0,-4); // eliminate the  ["] => &quot; [<] => &lt; [>] => &gt; [&] => &amp;

// <p><em><small>(Beta. Content is complete, fully indexed and partially formatted --- DRP)</small></em></p>

// make all css for kf explicit with own namespace prefix so no conflict
// Popup over defined terms with web links (like jospar.com)
// add in css from database
// Separate out <asides>
// Always show level should come from source document
// Add Next Back buttons that don't move
// Beta flag for contenti

// CHECK that the text is complete.


require_once "config.php";
define (NO_OF_RELATED,5);
require_once "include.php";

// Handle redirection to an anchor
$a = filterinput('%[\w]{1,32}%', 'a');
$d = filterinput('%[\d]+%', 'd');
if ($a and $d) {
	$redirectpage = cachequery("select p.id, p.permalink, p.runoftext from pages p, anchors a where  (p.id = a.page_id or p.id = a.page_id-1) and a.document_id = %d and a.anchor = '%s' order by p.id desc;",array($d,$a));
	//print_r($redirectpage);exit;
	if ($redirectpage) {
		$usepage = ($redirectpage[0]['runoftext'])?1:0; // handle runoftext pages that don't have external id.
		header('Location: ?focus='.$redirectpage[$usepage]['permalink']);
		exit;
	} else {
		echo 'missing link.  please press "Back"';
		exit;
	}
}


$focus = filterinput('%[\w-]{1,32}%', 'focus');
$popular = filterinput('%[\d-]{1}%', 'popular');
$swords = extractallinput('%[\w]+%', 's');
$s = implode(' ',$swords[0]);

if (!$focus) {
	$focus="nfpr-nfpr";
}

$documents = cachequery("select d.* from documents d, pages p where d.id = p.document_id and  p.permalink='%s';",array($focus));
if (!$documents) {
	echo "Document Not Found";
	exit;
} 

$results = cachequery("select * from pages where document_id = %d order by id;",array($documents[0]['id']));
foreach ($results as $index => $result) { #index by 'id'
	$page2result[$result['permalink']] = $index;
}

$search_result= '';
if ($s) {
	$search_results = cachequery("SELECT group_concat(id ORDER BY id SEPARATOR ', ') as search_result
	FROM (select id from pages WHERE MATCH (content) AGAINST ('%s' WITH QUERY EXPANSION ) LIMIT 7) r;",array($s));
	$search_result = $search_results[0]['search_result'];
	if (!$search_result) {
		$search_query = "SELECT group_concat(id ORDER BY id SEPARATOR ', ') AS search_result FROM (SELECT id, IF(content LIKE '%%".$s."%%',10,0)";
		foreach (explode(" ",$s) as $sword) {
			$search_query .= "+IF(content LIKE '%%".$sword."%%',1,0)";
		}
		$search_query .= "AS matchcount FROM pages ORDER BY matchcount DESC, id LIMIT 7)  r;";
		$search_results = cachequery($search_query);
		$search_result = $search_results[0]['search_result'];
	}
}
if ($popular) {
	$popular_results = cachequery("SELECT group_concat(page_id ORDER BY page_id SEPARATOR ', ') as popular_list
	FROM (select page_id from permalinks order by popularity desc LIMIT 7) r;");
	$popular_list = $popular_results[0]['popular_list'];

}

$pagecounts = cachequery("select sum(popularity) as pagecount from permalinks ;");
$pagecount = $pagecounts[0]['pagecount'];

require 'header.php';
?>
<div id="interface" class="rounded-corners">
<div id="content" >
<!--[if lte IE 7]><p style="color: #f00000; font-size:125%;"><span style="font-weight: bold;">ATTENTION! Sorry to say, but this browser is just not able to display this site.</span><br /> <span style="color:green;"><small>We suggest <strong>Internet Explorer 8+</strong> or a recent version of <strong>Firefox, Chrome, Safari,</strong> or <strong>Opera</strong> browsers!</small></span></p><![endif]-->
<a class="a2a_dd" href="http://www.addtoany.com/share_save"><img src="http://static.addtoany.com/buttons/share_save_171_16.png" width="171" height="16" border="0" alt="Share/Bookmark"/></a><script type="text/javascript" src="http://static.addtoany.com/menu/page.js"></script>
<p><a class="nextprev" href="?focus=<?php echo $results[$page2result[$focus]]['prevleaf'] ?>" title="Previous Page">&larr;</a></p>
<?php
# for this section, if it is a branch (or heading) then output the first leaf node with actual text.  This will contain
# the headings.
$thisleaf = firstLeaf($results,$page2result[$focus]);
echo strtr($results[$thisleaf]['content'], $trans);
?>
<p><a class="nextprev" href="?focus=<?php echo $results[$page2result[$focus]]['nextleaf'] ?>" title="Next Page">&rarr;</a>
</p>
	
<p class="ack"><em><?php echo $documents[0]['documenttitle']; ?></em> &copy; <?php echo $documents[0]['copyrightby']; ?>  the original text may be downloaded from 
	<a href="<?php echo $documents[0]['canonicalurl']; ?>">here</a>.
</p>

</div>
<div id="search" class="rounded-corners">
	
<form id=searchform" method="get" class="searchform" action="">
<input type="text" style="width: 200px; background: url('magglass.png') white no-repeat scroll left center; padding-left:20px;  font-size:100%" 
value="<?php  
	$nulls = 'Search the content';
	if ($s) {
		print $s;
	} else {
		print $nulls;
	} ?>" onload="if
(this.value=='') this.value='<?php print $nulls ?>'" onfocus="if
(this.value=='<?php print $nulls ?>') this.value=''" onblur="if
(this.value=='') this.value='<?php print $nulls ?>'" name="s" />&nbsp;
<input type="submit" class="rounded-corners" style="background: #f0fff0; color: #008000;" value="Search" />
<input type="hidden" name="focus" value="<?php print $focus; ?>" />
</form>
</div>
<div  id="kbrowser">
<p id="key">highlight: 
	<?php if (!$s and !$popular) { ?>
	<span style="background: url('focus_blue.png');">related topics</span> 
	<?php } elseif ($popular) { ?>
	<span style="background: url('focus_orange.png');">most read</span>
	<?php } else { ?>
	<span style="background: url('focus_green.png');">search results</span> 
	<?php } ?>
&nbsp;<?php echo $pagecount; ?> page views. <a class="popularlink" title="Show most read content" href="?focus=<?php print $focus; ?>&popular=1">Most read</a>
<a class="nextprev" href="?focus=<?php echo $results[$page2result[$focus]]['prevleaf'] ?>" title="Previous Page">&larr;</a>
<a class="nextprev" href="?focus=<?php echo $results[$page2result[$focus]]['nextleaf'] ?>" title="Next Page">&rarr;</a>
<?php
if (!$search_result and !$popular) $therelated = getRelated($results, $page2result, $focus);
foreach ($results as $result) {
	if (!$result['runoftext']) {
		$focusclass = '';
		#echo 'L'.substr(trim($result['title']),0,1).'L';
		$kbtitle = substr($result['title'],0,66).((strlen($result['title'])>66)?'...':'');
		if (!is_numeric(substr(trim($result['title']),0,1))) $kbtitle = '&bull; '.$kbtitle;
		if ($result['level'] < 3) {
			$focusclass = 'index';
			}
	
		if ($results[$page2result[$result['permalink']]]['parentpage_id']==$results[$page2result[$focus]]['parentpage_id']) {
			$focusclass = 'sibling';
			}
		if ($results[$page2result[$result['permalink']]]['parentpage_id']==$results[$page2result[$focus]]['id']) {
			$focusclass = 'child';
			}
		if (in_array($result['id'], explode(",",$results[$page2result[$focus]]['ancestors']))) {
			$focusclass = 'ancestor';
			}
		if ($search_result) {
			if (in_array($result['id'], explode(",",$search_result))) {
				$focusclass = 'search';
			}
		} elseif ($popular) {
			if (in_array($result['id'], explode(",",$popular_list))) {
				$focusclass = 'popular';
			}
		} else {
			if (in_array($result['id'], $therelated)) {
				$focusclass = 'related';
			}
	  }
		if ($result['permalink']==$focus) {
			$focusclass = 'focus';
			}
			
		if ($focusclass) {
			echo '<p class="indexitem'.$result['level'].'"><a class="'.$focusclass.'"href="?focus='.$result['permalink'].'" title="'.$focusclass.'">'.$kbtitle.'</a></p>';
		}
	}
}
?>

</div>
</div>
<?php
/*
$theshown = array();
if ($search_result) {
	$theshown = $search_result;
} elseif (!$popular){
	$theshown = $therelated;
}
foreach ($theshown as $shown) {
	cachequery("update permalinks set popularity=popularity+1 where page_id = %d ;",array($shown));
}
*/
cachequery("update permalinks set popularity=popularity+1 where id = '%s' ;",array($focus));

?>   

<?php
require 'footer.php';
?>